using UnityEngine;
using System;
using System.Collections;
using System.Text;
using System.Net;
using System.Net.Sockets;


public class CSdSocket_UDP : CsdSocket_TCP{

    public EndPoint targetPoint = null;
    public EndPoint remotePoint = null;
    override public int HandleID()
    {
        if (targetPoint != null)
        {
            return targetPoint.GetHashCode();
        }
        return 0;
    }
    override public bool IsConnectionReady()
    {
        if (s != null)
        {
            return true;
        }
        return false;
    }
    override public int Send_buf(byte[] sendbuf, int length)
    {
        //sub peers should send ,by call this  method
        try
        {
            if (IsConnectionReady())
            {
                int sentsize = s.SendTo(sendbuf, length, 0, targetPoint);
                return sentsize;
            }
        }
        catch (System.Exception)
        {

        }
        return -1;
    }
    override public int Recv_buf()
    {
        //UnityEngine.Debug.Log("udp recv from");
        //only listening peer will call this method
        try
        {
            int bytes = s.ReceiveFrom(bytesReceivedTemp, bytesReceivedTemp.Length, 0, ref remotePoint);
            return bytes;
        }
        catch (SocketException e)
        {
            if (e.ErrorCode == 10035 || e.ErrorCode == 10022)
            {
                //nothing wrong
            }
            else
            {
                throw e;
            }
        }
        return -1;
    }
}
